//
//  BN_Mine_ParentData.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-6-6.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#define PATH_DOC_USERDATA [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"UserData"]

#import "BN_Mine_diffParentData.h"
#import <QuartzCore/QuartzCore.h>

@implementation BN_Mine_diffParentData {
    NSArray *files_;
    NSInteger replTime_;
    BN_MyInfoHelper *myInfoHelper_;
    NSDictionary *medalCommentDict_;
}

- (id)init {
    if (self = [super init]) {
        self.netArr = [[NSMutableArray alloc]initWithCapacity:0];
        self.favoArr = [[NSMutableArray alloc]initWithCapacity:0];
        if (!myInfoHelper_) {
            myInfoHelper_ = [[BN_MyInfoHelper alloc]init];
        }
        [self requestParentNetData];
    }
    return self;
}

- (void)preload {
    self.mineParentListRelad(YES);
}

- (void)toReloadParentList:(Mine_ParentListReload)mineParentList {
    self.mineParentListRelad = mineParentList;
}

- (UIView *)loadNavView {
    _mineNavView = [[[NSBundle mainBundle]loadNibNamed:@"BN_Mine_NavgationView" owner:self options:nil]objectAtIndex:0];
    if (self.favoArr.count <= 0) {
        _mineNavView.medalCountLabel.text = @"0";
        _mineNavView.commentCountLabel.text = @"0";
    }else {
        _mineNavView.medalCountLabel.text = [NSString stringWithFormat:@"%@",medalCommentDict_[@"medaCoun"]];
        _mineNavView.commentCountLabel.text = [NSString stringWithFormat:@"%@",medalCommentDict_[@"evalCoun"]];

    } // 宝宝勋章和老师周评数量
    _mineNavView.backgroundColor = [UIColor clearColor];
    _mineNavView.modifyBtn.hidden = YES;
    
    // 头像
    NSString *path = [NSString stringWithFormat:@"%@/userPhoto.png",PATH_DOC_USERDATA];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        UIImage *userPhotoImage = [UIImage imageWithContentsOfFile:path];
        _mineNavView.userPhotoImageView.image = userPhotoImage;
    }
    return _mineNavView;
}


#pragma mark
#pragma mark UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.favoArr.count <= 0) {
        return 1;
    }else {
        return self.favoArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        static NSString *identifier = @"BN_Mine_NavgationView";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        if (indexPath.row == 0) {
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell addSubview:[self loadNavView]];
        }
        return cell;
    }else {
        // 参数infoFlg 为动态版块还是通知版块
        NSString *infoFlag = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"infoFlg"]];
        if ([infoFlag isEqualToString:@"0"]) {
            // 配置动态cell
            static NSString *identifier = @"BN_ClassParentCell";
            BOOL nibsResistered = NO;
            if (!nibsResistered) {
                UINib *nib = [UINib nibWithNibName:NSStringFromClass([BN_ClassParentCell class]) bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:identifier];
                nibsResistered = YES;
            }
            BN_ClassParentCell *cell = (BN_ClassParentCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            
            for (UIView *view in cell.disPlayImageView.subviews) {
                [view removeFromSuperview];
            }
            for (UIView *view in cell.replView.subviews) {
                [view removeFromSuperview];
            }
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            
            cell.cellHeight = 0;
            cell.relpHeight = 0;
            cell.singleRelpHeight = 0;
            
            // 用户权限
            // NSInteger postUserType = [self.favoArr[indexPath.row][@"postUserType"] integerValue];

            // 用户名称
            cell.userNameLabel.text = self.favoArr[indexPath.row][@"postUserName"];
            
            // 发布时间
            NSString *dateStr = self.favoArr[indexPath.row][@"postDate"];
            NSRange rang = NSMakeRange(0, 19);
            NSString *strRang = [dateStr substringWithRange:rang];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            NSTimeZone *timeZone = [NSTimeZone localTimeZone];
            [formatter setTimeZone:timeZone];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *dateTime = [formatter dateFromString:strRang];
            cell.createTimeLabel.text = [IMB_TimeFormatModel timeFormat:dateTime];
            
            // 用户头像
            NSString * postHeadUrlStr = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"postHeadUrl"]];
            postHeadUrlStr = [THUMBNAIL_BASEURL stringByAppendingString:postHeadUrlStr];
            NSURL *postHeadUrl = [NSURL URLWithString:postHeadUrlStr];
            if (postHeadUrl) {
                [cell.userPhotoImageView setImageWithURL:postHeadUrl placeholderImage:[UIImage imageNamed:@"userPhoto"]];
                cell.userPhotoImageView.layer.masksToBounds = YES;
                cell.userPhotoImageView.layer.cornerRadius = 18;
            }else {
                cell.userPhotoImageView.image = [UIImage imageNamed:@"userPhoto"];
            }
            
            // 浏览次数 browTime
            NSString *browTime = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"browTime"]];
            if (![browTime isEqual:[NSNull null]]) {
                cell.browseTimeLabel.text = [NSString stringWithFormat:@"浏览%@次",browTime];
            }else {
                cell.browseTimeLabel.text = @"浏览0次";
            }
            
            // 是否收藏
            cell.favoFlg = [self.favoArr[indexPath.row][@"favoFlg"] integerValue];
            // 喜欢标记
            cell.praiFlg = [self.favoArr[indexPath.row][@"praiFlg"]intValue];
            // 喜欢数
            cell.praiTime = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"praiTime"]];
            // postId
            cell.postId = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"postId"]];
            // 评论数
            cell.replTime = [self.favoArr[indexPath.row][@"replTime"] integerValue];
            
            
            NSString *replTime = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"replTime"]];
            NSString *praiTime = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"praiTime"]];
            
            if (![replTime isEqual:[NSNull null]]) {
                for (UILabel *view in cell.pinglunBtn.subviews) {
                    if ([view isKindOfClass:[UILabel class]]) {
                        [view removeFromSuperview];
                    }
                }
                UILabel *pinlunLabel = [[UILabel alloc]init];
                switch (MAIN_VERSION) {
                    case 6:
                        pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                        break;
                    default:
                        pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);
                        break;
                }
                pinlunLabel.backgroundColor = [UIColor clearColor];
                UIColor *color = APP_OBJECT_GREEN_COLOR;
                pinlunLabel.textColor = color;
                pinlunLabel.font = [UIFont systemFontOfSize:12];
                pinlunLabel.text = replTime;
                [cell.pinglunBtn addSubview:pinlunLabel];
            }
            
            if (![praiTime isEqual:[NSNull null]]) {
                for (UILabel *view in cell.xihuanBtn.subviews) {
                    if ([view isKindOfClass:[UILabel class]]) {
                        [view removeFromSuperview];
                    }
                }
                UILabel *xihuanLabel = [[UILabel alloc]init];
                switch (MAIN_VERSION) {
                    case 6:
                        xihuanLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                        break;
                    default:
                        
                        xihuanLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);

                        break;
                }
                xihuanLabel.backgroundColor = [UIColor clearColor];
                UIColor *color = APP_OBJECT_GREEN_COLOR;
                xihuanLabel.textColor = color;
                xihuanLabel.font = [UIFont systemFontOfSize:12];
                xihuanLabel.text = praiTime;
                [cell.xihuanBtn addSubview:xihuanLabel];
            }
            [cell dealLikeBtnColorState];
            
            
            // 评论数组
            cell.replArr = self.favoArr[indexPath.row][@"repls"];
            cell.replTime = [self.favoArr[indexPath.row][@"replTime"] integerValue];
            
            // 文字内容
            NSString *postSubj = self.favoArr[indexPath.row][@"postSubj"];
            if (![postSubj isEqual:[NSNull null]]) {
                cell.contentTextLabel.text = postSubj;
            }
            
            // UI
            NSString *fileFlg = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"fileFlg"]];
            cell.fileFlg = fileFlg;
            NSArray *files = self.favoArr[indexPath.row][@"files"];
            if ([fileFlg isEqualToString:@"0"]) {
                [cell groupImageView:files];
            }else {
                [cell groupVideo:files];
            }
            
            // 控件失效
            cell.pinglunBtn.enabled = NO;
            cell.xihuanBtn.enabled = NO;
            cell.fenxiangBtn.enabled = NO;
            
            return cell;
        }else {
            // 配置通知cell
            static NSString *identifier = @"BN_SchoolNoticeCell";
            BOOL nibsRegistered = NO;
            if (!nibsRegistered) {
                UINib *nib = [UINib nibWithNibName:NSStringFromClass([BN_SchoolNoticeCell class]) bundle:nil];
                [tableView registerNib:nib forCellReuseIdentifier:identifier];
                nibsRegistered = YES;
            }
            BN_SchoolNoticeCell *cell = (BN_SchoolNoticeCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            for (UIView *view in cell.disPlayImageView.subviews) {
                [view removeFromSuperview];
            }
            for (UIView *view in cell.replView.subviews) {
                [view removeFromSuperview];
            }
            cell.cellHeight = 0;
            cell.singleRelpHeight = 0;
            cell.relpHeight = 0;
            cell.titleTextLabel.text = @"";
            cell.contentTextLabel.text = @"";
            
            // 权限
            // NSInteger notiUserType = [self.favoArr[indexPath.row][@"notiUserType"] integerValue];
            // 是否收藏
            cell.favoFlg = [self.favoArr[indexPath.row][@"favoFlg"] integerValue];
            // 通知ID
            cell.notiId = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"notiId"]];
            cell.praiFlg = [self.favoArr[indexPath.row][@"praiFlg"]intValue];
            NSString *replTimeStr = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"replTime"]];
            cell.replTime = [replTimeStr integerValue];
            
            // 班级或全校图片
            NSInteger classOrSchoolFlg = [self.favoArr[indexPath.row][@"notiUserType"] integerValue];
            switch (classOrSchoolFlg) {
                case ENUM_ROLE_LEADER:
                    cell.classSchoolImageView.image = [UIImage imageNamed:@"schoolflg"];
                    break;
                case ENUM_ROLE_CLASS_TEACHER:
                    cell.classSchoolImageView.image = [UIImage imageNamed:@"classflg"];
                    break;
                default:
                    break;
            }
            
            // 时间
            NSString *dateStr = self.favoArr[indexPath.row][@"postDate"];
            NSRange rang = NSMakeRange(0, 19);
            NSString *strRang = [dateStr substringWithRange:rang];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            NSTimeZone *timeZone = [NSTimeZone localTimeZone];
            [formatter setTimeZone:timeZone];
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *dateTime = [formatter dateFromString:strRang];
            cell.createTimeLabel.text = [IMB_TimeFormatModel timeFormat:dateTime];
            NSString *replTime = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"replTime"]];
            NSString *praiTime = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"praiTime"]];
            cell.praiTime = praiTime;
            if (![replTime isEqual:[NSNull null]]) {
                for (UILabel *view in cell.pinglunBtn.subviews) {
                    if ([view isKindOfClass:[UILabel class]]) {
                        [view removeFromSuperview];
                    }
                }
                UILabel *pinlunLabel = [[UILabel alloc]init];
                switch (MAIN_VERSION) {
                    case 6:
                        pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                        break;
                    default:
                        
                        pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);

                        break;
                }
                pinlunLabel.backgroundColor = [UIColor clearColor];
                UIColor *color = APP_OBJECT_GREEN_COLOR;
                pinlunLabel.textColor = color;
                pinlunLabel.font = [UIFont systemFontOfSize:12];
                pinlunLabel.text = replTime;
                [cell.pinglunBtn addSubview:pinlunLabel];
            }
            
            if (![praiTime isEqual:[NSNull null]]) {
                for (UILabel *view in cell.xihuanBtn.subviews) {
                    if ([view isKindOfClass:[UILabel class]]) {
                        [view removeFromSuperview];
                    }
                }
                UILabel *xihuanLabel = [[UILabel alloc]init];
                switch (MAIN_VERSION) {
                    case 6:
                        xihuanLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                        break;
                    default:
                        
                        xihuanLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);

                        break;
                }
                xihuanLabel.backgroundColor = [UIColor clearColor];
                UIColor *color = APP_OBJECT_GREEN_COLOR;
                xihuanLabel.textColor = color;
                xihuanLabel.font = [UIFont systemFontOfSize:12];
                xihuanLabel.text = praiTime;
                [cell.xihuanBtn addSubview:xihuanLabel];
            }
            [cell dealLikeBtnColorState];
            
            
            // 评论数组
            cell.replArr = self.favoArr[indexPath.row][@"repls"];
            
            // 文字内容
            NSString *postSubj = self.favoArr[indexPath.row][@"postSubj"];
            if (![postSubj isEqual:[NSNull null]]) {
                cell.contentTextLabel.text = postSubj;
            }
            
            NSArray *files = self.favoArr[indexPath.row][@"files"];
            [cell contentTextToGroupView:files];
            
            // 控件失效
            cell.pinglunBtn.enabled = NO;
            cell.xihuanBtn.enabled = NO;
            cell.fenxiangBtn.enabled = NO;
            return cell;
        }
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 180;
    }else {
        NSString *infoFlag = [NSString stringWithFormat:@"%@",self.favoArr[indexPath.row][@"infoFlg"]];
        if ([infoFlag isEqualToString:@"0"]) {
            BN_ClassParentCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
            return cell.cellHeight;
        }else {
            BN_SchoolNoticeCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
            return cell.cellHeight;
        }
    }
    return 0;
}

#pragma mark
#pragma mark 刷新
- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // 上拉加载
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 下拉刷新
    [self requestParentNetData];
    [refreshView endRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    switch ([refreshView viewType]) {
        case -1:
            [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0];
            break;
        case 1:
            [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0];
            break;
        default:
            break;
    }
}

// 刷新完毕
- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    NSLog(@"刷新完毕");
}

// 监听刷新状态的变
- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            break;
            
        case MJRefreshStatePulling:
            break;
            
        case MJRefreshStateRefreshing:
            break;
        default:
            break;
    }
}

#pragma mark
#pragma mark 请求家长首页数据
- (void)requestParentNetData {
    __weak typeof(self) weakSelf = self;
    myInfoHelper_.queryParentHomeListCompleteHandler = ^(id result,NSString *errMsg){
        if (errMsg) {
            // [blockSelf_ showTopMessage:errMsg];
        }else{
            [weakSelf receiveParentNetData:result];
        }
    };
    [myInfoHelper_ refreshParentHomeInfoList];
}

// 正式修改_目前单个宝宝_家长记录宝宝ID
- (void)receiveParentNetData:(id)info {
    self.netArr = (NSMutableArray *)info;
    medalCommentDict_ = (NSDictionary *)self.netArr[0];

    if ([medalCommentDict_[@"chilId"] isEqual:[NSNull null]]) {
        [[NSUserDefaults standardUserDefaults]setObject:medalCommentDict_[@"chilId"] forKey:USERDEFAULTS_BABY_ID];
        [[NSUserDefaults standardUserDefaults]synchronize]; // 记录孩子Id
    }

    [self.netArr removeObjectAtIndex:0];
    self.favoArr = self.netArr;
    self.mineParentListRelad(YES);
}

- (void)releaseResource {
    _netArr = nil;
    _favoArr = nil;
    files_ = nil;
    medalCommentDict_ = nil;;
    _mineParentListRelad = nil;
    replTime_ = 0;
    [myInfoHelper_ cancleQueryEvalList];
}

- (void)dealloc
{
    [self releaseResource];
    NSLog(@"家长首页dataSource 释放...");
}

@end
